<?php

namespace App\Services\Code;

use App\Models\Attachment;
use App\Notifications\CodeNotification;
use Auth;
use Illuminate\Contracts\Container\BindingResolutionException;
use SmsService;
use App\Models\User;
use Cache;

/**
 * 验证码处理
 * @package App\Services\Code
 */
class CodeService
{
    /**
     * 发送手机验证码
     * @param mixed $mobile
     * @return mixed
     * @throws BindingResolutionException
     */
    public function mobile($mobile)
    {
        $data = [
            'template' => config('site.sms.aliyun.template'),
            'data' => [
                'code' => $this->code($mobile),
                'product' => config('site.sms.product')
            ],
        ];
        return SmsService::send($mobile, $data);
    }

    /**
     * 邮件验证码
     * @param mixed $email
     * @return void
     * @throws BindingResolutionException
     */
    public function email($email)
    {
        $user = new User;
        $user->email = $email;
        return $user->notify(new CodeNotification($this->code($email)));
    }

    /**
     * 生成验证码
     * @return int
     */
    public function code($account)
    {
        $code =  mt_rand(1000, 9999);
        Cache::put($this->cacheName($account), $code, now()->addMinutes(10));
    }

    /**
     * 缓存KEY
     * @param mixed $account
     * @return string
     */
    public function cacheName($account)
    {
        return 'validate-code-' . $account;
    }

    /**
     * 验证码校对
     * @param mixed $account
     * @param mixed $value
     * @return bool
     */
    public function check($account, $value)
    {
        return Cache::get($this->cacheName($account)) == $value;
    }
}
